﻿/*
 * Luu thong so cau hinh cho Polygon
 */
viettel.PolygonEditor = function (_polygon) {
    this.CLASSNAME = "viettel.PolygonEditor";

    var imgMarkerEdit = "../Images/images/edit_feature_marker.png";
    var imgMiddleMarkerEdit = "../Images/images/edit_feature_middle_marker.png";
    var imgMarkerBack = "../Images/images/undo_edit_feature.png";

    var that = this;
    var polygon = _polygon;
    var map = null;                 // Luu thong tin doi tuong ban do
    var paths = null;               // Luu toa do polygon
    var tmpPolygon = null;          // Polygon tam thoi, hien thi khi dang keo tha
    var editMarkers = [];           // Luu cac Marker su dung de chinh sua
    var oldPolygonInfo = null;      // Luu thong tin cu cua doi tuong
    var polygonListeners = [];      // Mang luu cac listener bat mot so su kien
    var isPolygonDragging = false;

    // Cap nhat cac vi tri chinh sua cho Circle
    var createPolygonMarkers = function () {
        clearPolygonMarkers();

        // Tao cac Marker giup chinh sua doi tuong
        var marker;
        var num = paths.getLength();
        for (var i = 0; i < num; i++) {
            var path = paths.getAt(i);
            var length = path.getLength();
            for (var j = 0; j < length; j++) {
                // Tao diem dinh
                for (var k = 0; k < 2; k++) {
                    var pt = path.getAt(j).clone();
                    var imgMarkerUrl = imgMarkerEdit;
                    if (k == 1) {
                        // Diem middle
                        var pt1 = pt;
                        var pt2 = path.getAt((j + 1) % length);
                        pt = new viettel.LatLng((pt1.lat() + pt2.lat()) / 2, (pt1.lng() + pt2.lng()) / 2);
                        imgMarkerUrl = imgMiddleMarkerEdit;
                    }
                    marker = new viettel.Marker({
                        map: map,
                        icon: new viettel.MarkerImage(imgMarkerUrl, null, null, new viettel.Point(6, 6), new viettel.Size(12, 12)),
                        position: pt,
                        draggable: true,
                        clickable: true
                    });
                    marker.markerInfo = {};
                    marker.markerInfo.type = (k == 1 ? "middle" : "pole");
                    marker.markerInfo.pathIdx = i;          // Chua index cua Path
                    marker.markerInfo.pointIdx = j;         // Chua index cua diem trong Path
                    marker.markerInfo.eventListeners = [];
                    marker.markerInfo.eventListeners.push(viettel.Events.addListener(marker, "dragstart", function (evt) {
                        handlerMarkerEvent("dragstart", evt);
                    }));
                    marker.markerInfo.eventListeners.push(viettel.Events.addListener(marker, "drag", function (evt) {
                        handlerMarkerEvent("drag", evt);
                    }));
                    marker.markerInfo.eventListeners.push(viettel.Events.addListener(marker, "dragend", function (marker) {
                        handlerMarkerEvent("dragend", marker);
                    }));

                    var tenDB = $("#selectDiBanDieuTra").val();


                    editMarkers.push(marker);
                }
            }
        }

        // Tao marker de quay lai thao tac cu
        marker = new viettel.Marker({
            map: map,
            icon: new viettel.MarkerImage(imgMarkerBack, null, null, new viettel.Point(40, 13), new viettel.Size(30, 27)),
            position: new viettel.LatLng(0, 0),
            draggable: false,
            clickable: true,
            visible: false
        });
        marker.markerInfo = {};
        marker.markerInfo.type = "back";
        marker.markerInfo.eventListeners = [];
        marker.markerInfo.eventListeners.push(viettel.Events.addListener(marker, "click", function (evt) {
            handlerMarkerEvent("click", evt);
        }));
        editMarkers.push(marker);
    }

    // Lay marker tuong ung voi kieu
    var getPolygonMarker = function (type) {
        for (var i = 0; i < editMarkers.length; i++) {
            if (editMarkers[i].markerInfo.type == type) {
                return editMarkers[i];
            }
        }
        return null;
    }

    // Xoa toan bo Markers trung gian
    var clearPolygonMarkers = function () {
        for (var i = 0; i < editMarkers.length - 1; i++) {
            var marker = editMarkers[i];
            for (var j = 0; j < marker.markerInfo.eventListeners.length; j++) {
                viettel.Events.removeListener(marker.markerInfo.eventListeners[j]);
            }
            marker.setMap(null);
        }
        editMarkers = [];
    }

    // Quay ve trang thai truoc
    var backChanged = function () {
        if (polygon != null && oldPolygonInfo != null) {
            // Cap nhat doi tuong duong tron ve trang thai cu
            polygon.setOptions({
                paths: oldPolygonInfo.paths
            });
            // Ham setOptions khong ban su kien ra vi the can goi ham nay de ban su kien ra
            viettel.Events.trigger(polygon, "paths_changed");
        }

        clearBackChanged();
    }

    // Xoa cac thong tin lien quan den thao tac Back
    var clearBackChanged = function () {
        // An marker thuc hien thao tac Back
        var backMarker = getPolygonMarker("back");
        if (backMarker != null && backMarker.getMap() != null) {
            // backMarker.setMap(null);
            backMarker.setVisible(false);
        }

        // Xoa thong tin lien quan den thao tac Back
        oldPolygonInfo = null;
    }

    // Ve lai
    var handlerMarkerEvent = function (eventName, evt) {
        var marker = evt.object;
        if (eventName == "dragend") {
            updateMarkerDragging(null, evt.latLng, eventName);
        }
        if (eventName == "dragstart" || eventName == "drag") {
            updateMarkerDragging(marker, marker.getPosition(), eventName);
        }
        else if (eventName == "click") {
            backChanged();
        }
    }

    // Tao doi tuong Circle tam
    var createTmpPolygon = function () {
        var opts = {
            paths: paths,
            strokeColor: polygon.getOptions().strokeColor,
            strokeWeight: polygon.getOptions().strokeWeight,
            strokeOpacity: 0.5,
            fillOpacity: 0,
            visible: false
        }
        tmpPolygon = new viettel.Polygon(opts);
    }

    // Xoa doi tuong Circle tam
    var clearTmpPolygon = function () {
        if (tmpPolygon != null) {
            tmpPolygon.setMap(null);
            tmpPolygon = null;
        }
    }

    // Cap nhat lai thong tin cho doi tuong
    var updateMarkerDragging = function (marker, latLng, eventName) {
        if (eventName == "dragstart" || eventName == "drag") {
            // Dang keo marker
            if (eventName == "dragstart" && marker.markerInfo.type == "middle") {
                marker.markerInfo.pointIdx++;
                paths.getAt(marker.markerInfo.pathIdx).insertAt(marker.markerInfo.pointIdx, latLng);
            }
            else {
                paths.getAt(marker.markerInfo.pathIdx).setAt(marker.markerInfo.pointIdx, latLng);
            }
            tmpPolygon.setOptions({
                paths: paths,
                visible: true
            });
            if (tmpPolygon.getMap() == null) {
                tmpPolygon.setMap(map);
            }
        }
        else {
            // Da tha marker
            // Luu thong tin cu
            var tmpPolygonInfo = {};
            tmpPolygonInfo.paths = polygon.getPaths();
            tmpPolygonInfo.position = new viettel.LatLng(latLng.lat(), latLng.lng());

            // Xoa duong tron tam
            tmpPolygon.setOptions({ map: null });

            // Cap nhat toa do
            polygon.setPaths(paths);
            
            return;
            // Hien thi nut Back
            //oldPolygonInfo = tmpPolygonInfo;
            //var backMarker = getPolygonMarker("back");
            //if (backMarker != null) {
            //    backMarker.setOptions({
            //        position: oldPolygonInfo.position,
            //        visible: true
            //    });
            //    if (backMarker.getMap() == null) {
            //        backMarker.setMap(map);
            //    }
            //}
        }
    }

    // Goi de cap nhat lai khi co thay doi center hoac radius
    var updatePolygonChannged = function () {
        clearBackChanged();

        map = polygon.getMap();
        paths = null;
        if (polygon.getPaths() != null) {
            paths = polygon.getPaths().clone();
        }
        if (map == null || paths == null) return false;

        if (!isPolygonDragging) {
            // Tao lai Marker
            clearPolygonMarkers();
            createPolygonMarkers();
            return true;
        }
        return false;
    }

    // Kich hoat che do chinh sua duong tron
    this.activate = function () {
        this.deactivate();
        map = polygon.getMap();
        paths = null;
        if (polygon.getPaths() != null) {
            paths = polygon.getPaths().clone();
        }
        if (map == null || paths == null) return false;

        createTmpPolygon();
        createPolygonMarkers();

        polygonListeners.push(viettel.Events.addListener(polygon, "dragstart", function (evt) {
            isPolygonDragging = true;
            clearBackChanged();
            that.display(false);
        }));
        polygonListeners.push(viettel.Events.addListener(polygon, "dragend", function (evt) {
            that.display(true);
            isPolygonDragging = false;
            updatePolygonChannged();
        }));

        return true;
    }

    // Huy che do chinh sua duong trong
    this.deactivate = function () {
        for (var i = 0; i < polygonListeners.length; i++) {
            viettel.Events.removeListener(polygonListeners[i]);
        }
        polygonListeners = [];

        clearPolygonMarkers();
        clearTmpPolygon();
        map = null;
        paths = null;
    }

    // Hien/An tat ca cac doi tuong su dung de edit duong tron
    this.display = function (isShow) {
        for (var i = 0; i < editMarkers.length; i++) {
            var marker = editMarkers[i];
            marker.setVisible(isShow);
        }
        if (tmpPolygon != null) {
            tmpPolygon.setVisible(isShow);
        }
    }

    // Goi de cap nhat khi co su thay doi duong tron va ban kinh o ngoai
    this.updateGeography = function () {
        updatePolygonChannged();
    }
}